# -*- coding: utf-8 -*-
import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pylons.decorators import validate
from pylons.decorators import jsonify
from pylons import session
import webhelpers.paginate as paginate
from formencode import validators
from formencode import htmlfill
from formencode import *
from pythonblog.lib.base import BaseController, render
from pythonblog.service import user_service, content_service, section_service
from pythonblog.controllers import custom_formatter
from pythonblog.controllers.dispatcher import DispatcherController
from pythonblog.model.content import *
from pythonblog.model.navigation import *
import pythonblog.lib.helpers as h

log = logging.getLogger(__name__)

class PostForm(Schema):    
    allow_extra_fields = True
    filter_extra_fields = True
    id = validators.Int(strip=True) 
    title = validators.String(strip=True, not_empty=True, min=1, max=50)
    abstract = validators.String(strip=True, min=0, max=1000)
    content = validators.String(strip=True, min=0, max=50000)
    type = validators.Int(strip=True, min=1, max=4) 
    section_id = validators.Int(strip=True)
    tags = validators.String(strip=True)

class PostController(BaseController):
    
    def __before__(self):
        sub_domain = self.get_sub_domain(request.environ)
        if self._is_home(sub_domain):
            if self.get_action(request.environ) != 'view' and \
                self.get_action(request.environ) != 'digg' :
                abort(404)

            if self.get_action(request.environ) == 'view':
                c.top_users = user_service.get_top_users()
                c.recommand_posts = content_service.get_recommand_posts()
        else:
            userInfo = user_service.get_user(sub_domain)
            if not userInfo:
                abort(404)

            c.userInfo = userInfo
            c.blogInfo = content_service.get_blog_info(userInfo.id)
        
    def view(self, id):
        id = long(id)
        if not content_service.is_post_exist(id):
            abort(404)
        c.post = content_service.get_post(id)
        content_service.update_post_viewTimes(id)
        c.comments = paginate.Page(
                content_service.get_comments(id),
                page=self._get_page(),
                items_per_page = 20
        )
        if c.userInfo:
            return render('/derived/blog/post.html')
        else:
            section = section_service.get_section(c.post.section_id)
            #type = section_service.get_type(c.post.type)
            c.section_id = section.id
            self._set_menu()
            return render('/derived/section/post.html')

    @jsonify
    def digg(self, id):
        post_id = long(id)
        promote = int(request.params.get('promote'))
        post = content_service.get_post(post_id)
        if not post:
            abort(404)

        if not content_service.is_user_digged(post_id, h.get_user_identifier()):
            visit = VisitorTrace()
            visit.post_id = post_id
            visit.userIdentifier = h.get_user_identifier()
            if promote == 1:
                visit.promote = 1
            else:
                visit.promote = 0
            content_service.add_digg_to_cache(visit)
            meta.Session.add(visit)
            meta.Session.commit()

        t = u"""<h3 class="digged"><span class="digg">%s顶</span><br/><span class="bury">%s踩</span></h3>"""\
            %(post.promotes_count, post.demotes_count)
        t2 = u"""<div class="digged"><strong>%s</strong> <br/>顶</div>"""%post.promotes_count
        return { 'flag': 1, 'id': post_id, 'html': t, 'html2': t2}
    
    def drafts(self):
        self.validate(c.userInfo.userName, request.environ)
        c.drafts = paginate.Page(
            content_service.get_drafts(c.userInfo.id),
            page=self._get_page(),
            items_per_page = 40,
            item_count = None,
            sqlalchemy_session = meta.Session
        )
        return render('/derived/blog/drafts.html')
    
    def edit(self, id):
        id = long(id)
        self.validate(c.userInfo.userName, request.environ)
        c.is_posted = True
        if not content_service.is_post_exist(id):
            abort(404)
        c.post = content_service.get_post(id)
        return self._edit_post()

    @jsonify
    def delete(self, id):
        id = long(id)
        self.validate(c.userInfo.userName, request.environ)
        title = content_service.delete_draft(id)
        session['flash_msg'] = u'"%s" 已经被成功删除！'%title
        session.save()
        redirect_to(controller='post', action='drafts', sub_domain=c.userInfo.userName)
    
    def edit_draft(self, id):
        id = long(id)
        self.validate(c.userInfo.userName, request.environ)
        draft = content_service.get_post_from_db(id)
        if not draft:
            abort(404)
        c.post = draft
        return self._edit_post()
    
    def _edit_post(self):
        defaults = {'id': c.post.id,
                    'title': c.post.title,
                    'type': c.post.type,
                    'section_id': c.post.section_id,
                    'section_id_show': section_service.get_section(c.post.section_id).name,
                    'tags': c.post.tags_display,
                    'abstract': c.post.abstract,
                    'content': c.post.content
                   }

        return htmlfill.render(render('/derived/blog/new.html'), defaults = defaults)

    def new(self):
        self.validate(c.userInfo.userName, request.environ)
        return render('/derived/blog/new.html')
    
    @validate(schema=PostForm(), form='new', post_only=False, 
              on_get=True, auto_error_formatter=custom_formatter)
    def save(self):
        self.validate(c.userInfo.userName, request.environ)
        id = self._save_post(1)
        section_id = self.form_result['section_id']
        post_info = content_service.get_section_first_post(section_id)
        if post_info.id == id:
            section = section_service.get_section(section_id)
            session['flash_msg'] = u'您的该篇文章已经在<a href="%s">%s</a>专栏置顶！'%(h.url_for_www('section', section_path=section.path), section.name)
            session.save()
        redirect_to(controller='post', action='view', id=id, sub_domain=c.userInfo.userName)
    
    @validate(schema=PostForm(), form='new', post_only=False, 
              on_get=True, auto_error_formatter=custom_formatter)
    def save_draft(self):
        self.validate(c.userInfo.userName, request.environ)
        self._save_post(2)
        redirect_to(controller='post', action='drafts', sub_domain=c.userInfo.userName)
    
    def _save_post(self, status):
        if self.form_result['id']:
            post = content_service.get_post_from_db(self.form_result['id'])
            if not post:
                abort(404)
        else:
            post = Post()
        post.user_id = c.userInfo.id
        post.title = self.form_result['title']
        post.content = self.form_result['content']
        post.abstract = self.form_result['abstract']
        post.updateDate = h.now()
        post.status = status
        post.type = self.form_result['type']
        post.section_id = self.form_result['section_id']
        post.title = self.form_result['title']
        if status == 1 and 'True' != request.params.get('is_posted', 'False'):
            post.createDate = h.now()

        tagNames = self.form_result['tags']
        import re
        re_split = re.compile(u'[,，]')
        tagNames = re_split.split(tagNames)
        validNames = []    
        for tagName in tagNames:
            tagName = tagName.strip()
            if tagName and validNames.count(tagName) < 1:
                validNames.append(tagName)
        post.tags = []
        for tagName in validNames:
            tag = Tag()
            tag.name = tagName
            post.tags.append(tag)
            
        meta.Session.flush()
        meta.Session.add(post)        
        meta.Session.commit()
        if status == 1:
            content_service.add_or_update_post_to_cache(post)
        return post.id
    
